package com.leyou.listener;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.leyou.config.SmsProperties;
import com.leyou.utils.SmsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@EnableConfigurationProperties(SmsProperties.class)
public class SmsListener {

    @Autowired
    private SmsUtils smsUtils;

    @Autowired
    private SmsProperties smsProperties;

    /**
     * 收到消息队列的消息后发送短信的方法
     *
     * @param msg:消息体是一个Map，里面有两个属性：发送短信需要的信息，有手机号和验证码
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "leyou.sms.queue", durable = "true"),
            exchange = @Exchange(value = "leyou.sms.exchange", ignoreDeclarationExceptions = "true"),
            key = {"sms.verify.code"}))
    public void listenerSms(Map<String, String> msg) throws Exception {
        // 如果为空放弃处理
        if (msg == null && msg.size() <= 0) {
            return;
        }
        // 获取手机和验证码
        String phone = msg.get("phone");
        String code = msg.get("code");

        // 如果为空放弃处理
        if (StringUtils.isBlank(phone) || StringUtils.isBlank(code)) {
            return;
        }
        // 短信发送
        SendSmsResponse sendResp = this.smsUtils.sendSms(phone, code, smsProperties.getSignName(), smsProperties.getVerifyCodeTemplate());

    }
}
